package com.ysq.www.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ysq.www.api.user.entity.Collect;
import com.ysq.www.api.user.mapper.CollectMapper;
import com.ysq.www.api.user.service.ICollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 收藏记录表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-08-18
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {

    @Autowired
    private CollectMapper collectMapper;


    /**
     * 收藏/取消收藏
     * @param userId 用户id
     * @param contentId 内容id
     * @param type 收藏类型：1资讯，2活动
     * @param isCollect 0取消收藏，1收藏
     * @return ResultMsg
     */
    @Override
    public ResultMsg addOrUpdateById(Integer userId, Integer contentId, Integer type, Integer isCollect) {
        //收藏
        if (isCollect == 1){
            QueryWrapper<Collect> wrapper = new QueryWrapper<>();
            wrapper.eq("type",type).eq("user_id",userId).eq("content_id",contentId);
            Collect ct = this.getOne(wrapper);
            if (ct != null){
                ct.setStatus(0);
                ct.setUpdateTime(Comm.getNow());
                this.updateById(ct);
            }else {
                Collect nc = new Collect();
                nc.setUserId(userId);
                nc.setType(type);
                nc.setContentId(contentId);
                nc.setCreateTime(Comm.getNow());
                nc.setUpdateTime(Comm.getNow());
                nc.setStatus(0);
                this.save(nc);
            }
        }else if (isCollect == 0){//取消收藏
            UpdateWrapper<Collect> wrapper = new UpdateWrapper<>();
            wrapper.set("status",1).set("update_time",Comm.getNow()).
                    eq("type",type).eq("user_id",userId).eq("content_id",contentId);
            collectMapper.update(null,wrapper);
        }
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("操作成功");
    }
}
